const qiNiuYun = require("qiniu");
const qiniu = require("qiniu-js");
const {AccessKey, SecretKey, bucket, overWriteFileName} = require("../config");
const path = require('path');
const opn = require('opn');
const config = new qiNiuYun.conf.Config();
const mac = new qiNiuYun.auth.digest.Mac(AccessKey, SecretKey);
const bucketManager = new qiNiuYun.rs.BucketManager(mac, config);
const {exec} = require("child_process");

const express = require('express');
const app = new express();
let host ;
let port;
const  server = app.listen(3000, "localhost", function() {
  // 监听的域名或者IP
   host = server.address().address;
  // 监听的端口
   port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
  const url = `http://${host}:${port}/static.html;`
  console.log("静态资源托管页面"+url);
  exec(`open ${url}`)
})
app.use(express.static(path.join(__dirname)))
app.get("/",function(req,res){
  res.redirect( 'http://%s:%s/static.html', host, port)
})
app.get('/qny/statics',async function(req, res) {
    // 响应请求
    let result = []
    try {
         result = await getAllFileName("")
    } catch (e) {
        console.log(e);
    }   
    res.send({
        data:result,
    });
});



function getAllFileName(prefix,limit=30){
   return new Promise((resolve,reject)=>{
    const arr = []
    const listOptions = {
        prefix,
        // limit,
    }

    bucketManager.listPrefix(bucket, listOptions, function(err, respBody, respInfo) {
        if (err) {
          throw err;
        }
        if (respInfo.statusCode == 200) {
          //如果这个nextMarker不为空，那么还有未列举完毕的文件列表，下次调用listPrefix的时候，
          //指定options里面的marker为这个值
          var items = respBody.items;
          items.forEach(function(item) {
            // console.log('http://qiniuyun.quancundexiwang.wang/'+item.key);
            arr.push('http://qiniuyun.quancundexiwang.wang/'+item.key)
            resolve(arr)
          });
        } else {
          reject({
              err_code:respInfo.statusCode,
              respBody,
          })
        }
      });
   })
}

getAllFileName("");